package com.tkmybatis.hfy.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @author ywt
 * @date 2016年10月19日 上午11:32:22
 * @version 1.0
 *
 */
@Slf4j
public final class MathUtil {
	private static volatile MathUtil mathUtil = null;
	
	/**
	 * 生成随机数
	 * @param length  随机数位数
	 * @return
	 */
	public static String getRandom(int length) {
		String x="";
        for(int n=0;n<length;n++ ) {
            x+=(int)(10*(Math.random()));
        }
        return x;
	} 
	
	public static MathUtil getInstance() {
		if (mathUtil == null) {
			synchronized (MathUtil.class) {
				if (mathUtil == null) {
					mathUtil = new MathUtil();
				}
			}
		}
		return mathUtil;
	}

	public static String encryptPassWordSHA(String clearlyPasssword) {
		try {
			MessageDigest sha = MessageDigest.getInstance("SHA");
			sha.update(clearlyPasssword.getBytes());
			return byte2hex(sha.digest());
		} catch (NoSuchAlgorithmException e) {
			log.error("error:",e);
		}
		return null;
	}

	public static String byte2hex(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		String temp = null;
		for (int i = 0; i < bytes.length; i++) {
			temp = Integer.toHexString(bytes[i] & 0xFF);
			if (temp.length() == 1) {
				result.append("0");
			}
			result.append(temp);
		}
		return result.toString();
	}

	/**
	 * 获取下一个值
	 * 
	 * @param number
	 * @return
	 */
	public static String getNextNumber(String number) {
		Integer length = number.length();
		Integer no = Integer.parseInt(number);
		Integer netNumber = no + 1;
		String nextNo = netNumber.toString();
		if (nextNo.length() < length) {
			Integer l = length - nextNo.length();
			for (int i = 0; i < l; i++) {
				nextNo = "0" + nextNo;
			}
		}
		return nextNo;
	}

	/**
	 * 集合分组
	 * @param list
	 * @param splitSize
	 * @return
	 */
	public static List<List<String>> split(List<String> list, Integer splitSize) {
		List<List<String>> results = new ArrayList<>();
		Integer length = list.size() / splitSize + 1;
		Integer size = list.size();
		for (int i = 0; i < length; i++) {
			List<String> nums = new ArrayList<>();
			int start = i * splitSize;
			int end = (i + 1) * splitSize;
			if (end > size) {
				end = size;
			}
			for (int k = start; k < end; k++) {
				nums.add(list.get(k));
			}
			results.add(nums);
		}
		return results;
	}

}
